<template>
    <div class="container">
        <Breadcrumb :items="['menu.common', 'menu.common.ann']" />
        <a-card :title="$t('menu.common.ann')">

            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加公告
                            </a-button>
                        </a-space>

                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle" @click="fetchData">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="标题" data-index="ann_title" />
                        <a-table-column title="内容" data-index="ann_content" :width="300">
                            <template #cell="{ record }">
                                <a-typography-paragraph :ellipsis="{ rows: 2, showTooltip: true }">
                                    {{ record.ann_content }}
                                </a-typography-paragraph>
                            </template>
                        </a-table-column>
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="更新时间" data-index="updated_at" :width="180" />
                        <a-table-column title="操作" align="center" :width="120">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="openModal(record)">
                                        编辑
                                    </a-link>
                                    <a-popconfirm position="left" content="确定要删除这个公告吗？" @ok="handleDelete(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" :title="formData.id ? '编辑公告' : '添加公告'" @before-ok="handleSubmit"
            @cancel="closeModal" :width="800">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-form-item field="ann_title" label="公告标题" :rules="[{ required: true, message: '请输入公告标题' }]">
                    <a-input v-model="formData.ann_title" placeholder="请输入公告标题" />
                </a-form-item>
                <a-form-item field="ann_content" label="公告内容" :rules="[{ required: true, message: '请输入公告内容' }]">
                    <div class="markdown-editor-container">
                        <v-md-editor v-model="formData.ann_content" @upload-image="handleUploadImage" :disabled-menus="[]" height="300px" style="width: 100%;" />
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryAnnList, submitAnnForm, delAnn, AnnRecord, AnnModel } from '@/api/ann';
import { uploadFile } from '@/api/upload';
import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import createEmojiPlugin from '@kangc/v-md-editor/lib/plugins/emoji/index';
import '@kangc/v-md-editor/lib/plugins/emoji/emoji.css';
import createTodoListPlugin from '@kangc/v-md-editor/lib/plugins/todo-list/index';
import '@kangc/v-md-editor/lib/plugins/todo-list/todo-list.css';
import createAlignPlugin from '@kangc/v-md-editor/lib/plugins/align/index';
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index';
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index';
import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';
import createHighlightLinesPlugin from '@kangc/v-md-editor/lib/plugins/highlight-lines/index';
import '@kangc/v-md-editor/lib/plugins/highlight-lines/highlight-lines.css';

// 配置v-md-editor
VMdEditor.use(githubTheme);
VMdEditor.use(createEmojiPlugin());
VMdEditor.use(createTodoListPlugin());
VMdEditor.use(createAlignPlugin());
VMdEditor.use(createLineNumbertPlugin());
VMdEditor.use(createCopyCodePlugin());
VMdEditor.use(createHighlightLinesPlugin());

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

const generateFormData = () => {
    return {
        id: 0,
        ann_title: '',
        ann_content: '',
    };
};

const formData = ref(generateFormData());

const renderData = ref<AnnRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const res = await queryAnnList({
            page: pagination.current,
            pageSize: pagination.pageSize,
        });
        renderData.value = res.data.list;
        pagination.total = res.data.total;
    } catch (err) {
        Message.error('获取公告列表失败');
    } finally {
        setLoading(false);
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const openModal = (record?: AnnRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            ann_title: record.ann_title,
            ann_content: record.ann_content,
        };
    } else {
        formData.value = generateFormData();
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
};

const handleSubmit = async (done: any) => {
    setLoading(true);
    try {
        const res = await submitAnnForm(formData.value);
        Message.success(res.msg || '操作成功');
        closeModal();
        fetchData();
        done(true);
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delAnn(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

// 富媒体编辑框图片上传方法
const handleUploadImage = async (event: any, insertImage: any) => {
    try {
        // 创建文件输入元素
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        
        input.onchange = async (e: any) => {
            const file = e.target.files[0];
            if (!file) {
                Message.warning('请选择要上传的图片');
                return;
            }

            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                Message.error('只能上传图片文件');
                return;
            }

            // 检查文件大小（限制为5MB）
            const maxSize = 5 * 1024 * 1024; // 5MB
            if (file.size > maxSize) {
                Message.error('图片大小不能超过5MB');
                return;
            }

            try {
                const uploadFormData = new FormData();
                uploadFormData.append('file', file);
                
                const { data } = await uploadFile(uploadFormData);
                
                // 插入图片到编辑器
                insertImage({
                    url: data.url,
                    alt: file.name,
                    title: file.name
                });
                
                Message.success('图片上传成功');
            } catch (err) {
                console.error('图片上传失败:', err);
                Message.error('图片上传失败，请重试');
            }
        };
        
        // 触发文件选择
        input.click();
    } catch (err) {
        console.error('图片上传失败:', err);
        Message.error('图片上传失败，请重试');
    }
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}

.markdown-editor-container {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    width: 100%;
}

.markdown-editor-container :deep(.v-md-editor) {
    border: none;
    width: 100%;
}

.markdown-editor-container :deep(.v-md-editor__toolbar) {
    border-bottom: 1px solid #f0f0f0;
}

.markdown-editor-container :deep(.v-md-editor__editor-wrapper) {
    border: none;
    width: 100%;
}
</style>

<script lang="ts">
export default {
    name: 'CommonAnn',
};
</script>
